import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../models/conversation.dart';
import '../models/message.dart';
import '../widgets/empty_state.dart';
import 'chat_page.dart';
import 'message_detail_page.dart';

/// 消息页面
class MessagesPage extends StatefulWidget {
  const MessagesPage({super.key});

  @override
  State<MessagesPage> createState() => _MessagesPageState();
}

class _MessagesPageState extends State<MessagesPage> with TickerProviderStateMixin {
  late final TabController _tabController;
  final RefreshController _conversationRefreshController = RefreshController();
  final RefreshController _systemMessageRefreshController = RefreshController();

  // 修改模拟会话数据
  final List<Conversation> _conversations = [
    Conversation(
      id: '1',
      name: '张先生',
      avatar: 'assets/images/avatar.png',
      customerAvatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=Felix&backgroundColor=b6e3f4',
      customerName: '张先生',
      orderType: '居民搬家',
      lastMessage: '好的，那就这么说定了',
      lastTime: '14:30',
      unread: 1,
      orderId: 'DD001',
    ),
    Conversation(
      id: '2',
      name: '李女士',
      avatar: 'assets/images/avatar.png',
      customerAvatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=Lucy&backgroundColor=ffdfbf',
      customerName: '李女士',
      orderType: '办公室搬迁',
      lastMessage: '请问什么时候到？',
      lastTime: '昨天',
      unread: 0,
      orderId: 'DD002',
    ),
  ];

  // 模拟系统消息数据
  final List<Message> _systemMessages = [
    Message(
      id: '1',
      title: '系统升级通知',
      content: '尊敬的用户，系统将于今晚24:00进行升级维护，预计持续2小时，请提前安排好工作。',
      time: '2024-03-20 10:00',
      type: MessageType.system,
    ),
    Message(
      id: '2',
      title: '节日通知',
      content: '春节期间（2024年2月9日-2月17日）暂停服务，2月18日恢复正常，给您带来不便敬请谅解。',
      time: '2024-02-05 15:30',
      isRead: true,
      type: MessageType.system,
    ),
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: 0,
    );

    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        // 标签页正在切换
      }
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _conversationRefreshController.dispose();
    _systemMessageRefreshController.dispose();
    super.dispose();
  }

  /// 构建会话项
  Widget _buildConversationItem(Conversation conversation) {
    return Dismissible(
      key: Key(conversation.id),
      direction: DismissDirection.endToStart,
      background: Container(
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20),
        color: Colors.red,
        child: const Icon(
          Icons.delete_outline,
          color: Colors.white,
        ),
      ),
      confirmDismiss: (direction) => _deleteConversation(conversation),
      child: Container(
        margin: const EdgeInsets.only(bottom: 1),
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: () => _navigateToChatPage(conversation),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  // 头像
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: Colors.grey[100],
                      shape: BoxShape.circle,
                    ),
                    child: conversation.customerAvatar != null
                        ? ClipOval(
                            child: Image.network(
                              conversation.customerAvatar!,
                              fit: BoxFit.cover,
                            ),
                          )
                        : Icon(
                            Icons.person_outline,
                            color: Colors.grey[400],
                          ),
                  ),
                  const SizedBox(width: 12),
                  // 会话信息
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Text(
                              conversation.customerName,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            const SizedBox(width: 8),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 6,
                                vertical: 2,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.grey[100],
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Text(
                                conversation.orderType,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[600],
                                ),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 4),
                        Row(
                          children: [
                            Expanded(
                              child: Text(
                                conversation.lastMessage,
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey[600],
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            const SizedBox(width: 8),
                            Text(
                              conversation.lastTime,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[400],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  // 未读标记
                  if (conversation.isUnread)
                    Container(
                      width: 8,
                      height: 8,
                      margin: const EdgeInsets.only(left: 8),
                      decoration: const BoxDecoration(
                        color: Color(0xFFFF5722),
                        shape: BoxShape.circle,
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建系统消息项
  Widget _buildSystemMessageItem(Message message) {
    return Dismissible(
      key: Key(message.id),
      direction: DismissDirection.endToStart,
      background: Container(
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20),
        color: Colors.red,
        child: const Icon(
          Icons.delete_outline,
          color: Colors.white,
        ),
      ),
      confirmDismiss: (direction) => _deleteSystemMessage(message),
      child: Container(
        margin: const EdgeInsets.only(bottom: 1),
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: () async {
              if (!message.isRead) {
                await _markAsRead(message);
              }
              if (!mounted) return;
              
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => MessageDetailPage(message: message),
                ),
              );
            },
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (!message.isRead)
                    Container(
                      width: 6,
                      height: 6,
                      margin: const EdgeInsets.only(top: 8, right: 8),
                      decoration: const BoxDecoration(
                        color: Color(0xFFFF5722),
                        shape: BoxShape.circle,
                      ),
                    ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Expanded(
                              child: Text(
                                message.title,
                                style: TextStyle(
                                  fontSize: 15,
                                  fontWeight: message.isRead ? FontWeight.normal : FontWeight.w500,
                                  color: message.isRead ? Colors.grey[600] : Colors.black87,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            const SizedBox(width: 8),
                            Text(
                              message.time,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[400],
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 4),
                        Text(
                          message.content,
                          style: TextStyle(
                            fontSize: 13,
                            color: Colors.grey[600],
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 跳转到聊天页面
  void _navigateToChatPage(Conversation conversation) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChatPage(
          conversation: conversation,  // 只传入 conversation 参数
        ),
      ),
    );
  }

  /// 删除会话
  Future<bool?> _deleteConversation(Conversation conversation) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除会话'),
        content: const Text('确定要删除这个会话吗？聊天记录将会被清空'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      setState(() {
        _conversations.removeWhere((c) => c.id == conversation.id);
      });
      return true;
    }
    return false;
  }

  /// 标记消息为已读
  Future<void> _markAsRead(Message message) async {
    try {
      // 模拟网络请求
      await Future.delayed(const Duration(milliseconds: 500));
      
      setState(() {
        final index = _systemMessages.indexWhere((m) => m.id == message.id);
        if (index != -1) {
          _systemMessages[index] = Message(
            id: message.id,
            title: message.title,
            content: message.content,
            time: message.time,
            isRead: true,
            type: message.type,
          );
        }
      });
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('操作失败，请重试'),
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  /// 删除系统消息
  Future<bool?> _deleteSystemMessage(Message message) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除消息'),
        content: const Text('确定要删除这条消息吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      setState(() {
        _systemMessages.removeWhere((m) => m.id == message.id);
      });
      return true;
    }
    return false;
  }

  /// 处理会话列表刷新
  Future<void> _onConversationRefresh() async {
    try {
      await Future.delayed(const Duration(seconds: 1));
      
      setState(() {
        _conversations.insert(0, Conversation(
          id: DateTime.now().toString(),
          name: '王先生',
          avatar: 'assets/images/avatar.png',
          customerAvatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=John&backgroundColor=c0aede',
          customerName: '王先生',
          orderType: '居民搬家',
          lastMessage: '新的会话消息',
          lastTime: '刚刚',
          unread: 0,
          orderId: 'DD003',
        ));
      });
      
      _conversationRefreshController.refreshCompleted();
    } catch (e) {
      _conversationRefreshController.refreshFailed();
    }
  }

  /// 处理会话列表加载更多
  Future<void> _onConversationLoading() async {
    try {
      await Future.delayed(const Duration(seconds: 1));
      
      setState(() {
        _conversations.addAll([
          Conversation(
            id: DateTime.now().toString(),
            name: '赵女士',
            avatar: 'assets/images/avatar.png',
            customerAvatar: 'https://api.dicebear.com/7.x/avataaars/png?seed=Sarah&backgroundColor=ffd5dc',
            customerName: '赵女士',
            orderType: '办公室搬迁',
            lastMessage: '历史会话消息',
            lastTime: '前天',
            unread: 0,
            orderId: 'DD004',
          ),
        ]);
      });
      
      _conversationRefreshController.loadComplete();
    } catch (e) {
      _conversationRefreshController.loadFailed();
    }
  }

  /// 处理系统消息刷新
  Future<void> _onSystemMessageRefresh() async {
    try {
      await Future.delayed(const Duration(seconds: 1));
      
      setState(() {
        _systemMessages.insert(0, Message(
          id: DateTime.now().toString(),
          title: '新系统通知',
          content: '这是一条新的系统通知内容。',
          time: '刚刚',
          type: MessageType.system,
        ));
      });
      
      _systemMessageRefreshController.refreshCompleted();
    } catch (e) {
      _systemMessageRefreshController.refreshFailed();
    }
  }

  /// 处理系统消息加载更多
  Future<void> _onSystemMessageLoading() async {
    try {
      await Future.delayed(const Duration(seconds: 1));
      
      setState(() {
        _systemMessages.addAll([
          Message(
            id: DateTime.now().toString(),
            title: '历史系统通知',
            content: '这是一条历史系统通知内容。',
            time: '2024-01-01 12:00',
            type: MessageType.system,
            isRead: true,
          ),
        ]);
      });
      
      _systemMessageRefreshController.loadComplete();
    } catch (e) {
      _systemMessageRefreshController.loadFailed();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(0.5),
          child: Container(
            color: Colors.grey[200],
            height: 0.5,
          ),
        ),
        title: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '会话'),
            Tab(text: '系统消息'),
          ],
          labelStyle: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
          unselectedLabelStyle: const TextStyle(
            fontSize: 15,
          ),
          labelColor: const Color(0xFFFF5722),
          unselectedLabelColor: Colors.grey,
          indicator: const BoxDecoration(),
          padding: EdgeInsets.zero,
          dividerColor: Colors.transparent,
          isScrollable: true,
          tabAlignment: TabAlignment.start,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // 会话列表
          _conversations.isEmpty
              ? EmptyState(
                  message: '暂无会话',
                  subMessage: '新的会话将会显示在这里',
                  icon: Icons.chat_bubble_outline,
                  onRefresh: _onConversationRefresh,
                )
              : SmartRefresher(
                  controller: _conversationRefreshController,
                  enablePullDown: true,
                  enablePullUp: _conversations.length >= 10,
                  header: ClassicHeader(
                    refreshStyle: RefreshStyle.Follow,
                    idleText: '下拉刷新',
                    refreshingText: '加载中...',
                    completeText: '刷新成功',
                    failedText: '刷新失败',
                    releaseText: '松开刷新',
                    height: 44,
                    spacing: 8,
                    iconPos: IconPosition.left,
                    textStyle: TextStyle(color: Colors.grey[600], fontSize: 12),
                    refreshingIcon: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
                      ),
                    ),
                  ),
                  footer: ClassicFooter(
                    loadStyle: LoadStyle.ShowAlways,
                    idleText: '上拉加载更多',
                    loadingText: '加载中...',
                    noDataText: '没有更多数据',
                    failedText: '加载失败',
                    canLoadingText: '松开加载更多',
                    height: 44,
                    spacing: 8,
                    iconPos: IconPosition.left,
                    textStyle: TextStyle(color: Colors.grey[600], fontSize: 12),
                    loadingIcon: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
                      ),
                    ),
                  ),
                  onRefresh: _onConversationRefresh,
                  onLoading: _onConversationLoading,
                  child: ListView.builder(
                    padding: EdgeInsets.zero,
                    itemCount: _conversations.length,
                    itemBuilder: (context, index) => 
                        _buildConversationItem(_conversations[index]),
                  ),
                ),
          // 系统消息列表
          _systemMessages.isEmpty
              ? EmptyState(
                  message: '暂无系统消息',
                  subMessage: '新的系统消息将会显示在这里',
                  icon: Icons.notifications_none,
                  onRefresh: _onSystemMessageRefresh,
                )
              : SmartRefresher(
                  controller: _systemMessageRefreshController,
                  enablePullDown: true,
                  enablePullUp: _systemMessages.length >= 10,
                  header: ClassicHeader(
                    refreshStyle: RefreshStyle.Follow,
                    idleText: '下拉刷新',
                    refreshingText: '加载中...',
                    completeText: '刷新成功',
                    failedText: '刷新失败',
                    releaseText: '松开刷新',
                    height: 44,
                    spacing: 8,
                    iconPos: IconPosition.left,
                    textStyle: TextStyle(color: Colors.grey[600], fontSize: 12),
                    refreshingIcon: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
                      ),
                    ),
                  ),
                  footer: ClassicFooter(
                    loadStyle: LoadStyle.ShowAlways,
                    idleText: '上拉加载更多',
                    loadingText: '加载中...',
                    noDataText: '没有更多数据',
                    failedText: '加载失败',
                    canLoadingText: '松开加载更多',
                    height: 44,
                    spacing: 8,
                    iconPos: IconPosition.left,
                    textStyle: TextStyle(color: Colors.grey[600], fontSize: 12),
                    loadingIcon: SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
                      ),
                    ),
                  ),
                  onRefresh: _onSystemMessageRefresh,
                  onLoading: _onSystemMessageLoading,
                  child: ListView.builder(
                    padding: EdgeInsets.zero,
                    itemCount: _systemMessages.length,
                    itemBuilder: (context, index) => 
                        _buildSystemMessageItem(_systemMessages[index]),
                  ),
                ),
        ],
      ),
    );
  }
} 